package com.aic.aicdetactor.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.CRC32;

import com.aic.aicdetactor.common.Setting;

import android.text.format.Time;



public class  SystemUtil {

	public static final int TIME_FORMAT_YYMMDDHHMM = 0;
	public static final int TIME_FORMAT_HHMM = 1;
	public static final int TIME_FORMAT_YYMMDD = 2;
	public static final int TIME_FORMAT_YYMMDD2 = 3;
	/**
	 * 
	 * @param type 0,yyyy-mm-dd hh:mm:ss;
	 * 1:hhmm;
	 * 2:yyyy-mm--dd
	 * @return
	 */
	public  static String getSystemTime(int type){
		String str = null;
		if(type ==TIME_FORMAT_YYMMDDHHMM){
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		str = df.format(new Date());
		}else if (type ==TIME_FORMAT_HHMM){
			Time t=new Time(); // or Time t=new Time("GMT+8"); 鍔犱笂Time Zone璧勬枡銆�  
			t.setToNow(); // 鍙栧緱绯荤粺鏃堕棿銆�  
			int year = t.year;  
			int month = t.month;  
			int date = t.monthDay;  
			int hour = t.hour; // 0-23  
			int minute = t.minute;  
			int second = t.second;  
			str  = (hour<10?("0"+hour):hour)+""+(minute<10?("0"+minute):minute);
		}else if(type ==TIME_FORMAT_YYMMDD){
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			str = df.format(new Date());
		}else if(type ==TIME_FORMAT_YYMMDD2){
			DateFormat df = new SimpleDateFormat("yyyyMMdd");
			str = df.format(new Date());
		}
		
		
		
		
		
		return str;
	}
	public static String createGUID(){
		String str = null;
		UUID uuid = UUID.randomUUID();		
		str = uuid.toString();
		return str;
	}
	
	public static List<Map<String, Object>> reverseListData(List<Map<String, Object>> inList){
		
		if(inList == null) return null;
		List<Map<String, Object>> OutList = new ArrayList<Map<String, Object>>();
		for(int i = inList.size()-1;i>=0;i--){
			OutList.add(inList.get(i));
		}
		inList.clear();
		inList.addAll(OutList);
		return inList;
	}
	public static String getDataRootStoragePath(){
		
		Setting setting = new Setting();
	
		return setting.getData_Root_Director();
	}
	
	
	public static boolean deleteFile(String filePath) {
	    File file = new File(filePath);
	        if (file.isFile() && file.exists()) {
	        return file.delete();
	        }
	        return false;
	    }
	
	public static void renameFile(String oldFileName,String destFileName){
		deleteFile(destFileName);
		File from =new File(oldFileName) ;
		if(from!=null){
		File to=new File(destFileName) ;
		from.renameTo(to) ;
		}
		
	}
	public static boolean deleteDirectory(String filePath) {
	    boolean flag = false;
	        //濡傛灉filePath涓嶄互鏂囦欢鍒嗛殧绗︾粨灏撅紝鑷姩娣诲姞鏂囦欢鍒嗛殧绗�
	        if (!filePath.endsWith(File.separator)) {
	            filePath = filePath + File.separator;
	        }
	        File dirFile = new File(filePath);
	        if (!dirFile.exists() || !dirFile.isDirectory()) {
	            return false;
	        }
	        flag = true;
	        File[] files = dirFile.listFiles();
	        //閬嶅巻鍒犻櫎鏂囦欢澶逛笅鐨勬墍鏈夋枃浠�(鍖呮嫭瀛愮洰褰�)
	        for (int i = 0; i < files.length; i++) {
	            if (files[i].isFile()) {
	            //鍒犻櫎瀛愭枃浠�
	                flag = deleteFile(files[i].getAbsolutePath());
	                if (!flag) break;
	            } else {
	            //鍒犻櫎瀛愮洰褰�
	                flag = deleteDirectory(files[i].getAbsolutePath());
	                if (!flag) break;
	            }
	        }
	        if (!flag) return false;
	        //鍒犻櫎褰撳墠绌虹洰褰�
	        return dirFile.delete();
	    }

	    /**
	     *  鏍规嵁璺緞鍒犻櫎鎸囧畾鐨勭洰褰曟垨鏂囦欢锛屾棤璁哄瓨鍦ㄤ笌鍚�
	     *@param filePath  瑕佸垹闄ょ殑鐩綍鎴栨枃浠�
	     *@return 鍒犻櫎鎴愬姛杩斿洖 true锛屽惁鍒欒繑鍥� false銆�
	     */
	public static boolean DeleteFolder(String filePath) {
	    File file = new File(filePath);
	        if (!file.exists()) {
	            return false;
	        } else {
	            if (file.isFile()) {
	            // 涓烘枃浠舵椂璋冪敤鍒犻櫎鏂囦欢鏂规硶
	                return deleteFile(filePath);
	            } else {
	            // 涓虹洰褰曟椂璋冪敤鍒犻櫎鐩綍鏂规硶
	                return deleteDirectory(filePath);
	            }
	        }
	    }
	public static byte[] hexStringToByteArray(String s) {
	    int len = s.length();
	    byte[] data = new byte[len / 2];
	    for (int i = 0; i < len; i += 2) {
	        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
	                             + Character.digit(s.charAt(i+1), 16));
	    }
	    return data;
	}
	public static float ByteArrayToFloat(byte[] bytes) {
		float value = ((((bytes[0] & 0xff) << 24 | (bytes[1] & 0xff)) << 16) | (bytes[2] & 0xff)) << 8 | (bytes[3] & 0xff);
	//	return Float.intBitsToFloat(i);
		return value;
	}
	
	public static float getTemperature(String s){
		byte[] bytes =hexStringToByteArray(s);
		return ByteArrayToFloat(bytes);
	}
	
	public static void writeFileToSD(String fileName, String StrContent)
			throws IOException {
		
		File file = new File(fileName);

		FileOutputStream outStream = new FileOutputStream(file);
		outStream.write(StrContent.getBytes("utf-8"));
		outStream.close();
	}  
	
	public static String openFile(String path) {
		if (null == path) {

			return null;
		}

		File file = new File(path);
		if (file.exists()) {
			try {
				StringBuffer sb = new StringBuffer();
				// HttpEntity entity = response.getEntity();
				InputStream is = new FileInputStream(path);// entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						is, "utf-8"));
				String data = "";

				while ((data = br.readLine()) != null) {
					sb.append(data);
				}
				String result = sb.toString();
				
				// return result.getBytes("UTF-8");
				return result;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}	


	/**
	 * 璁＄畻缁欏畾涓や釜鏃堕棿鐨勫樊
	 * 鍏ュ弬 time 鏍煎紡蹇呴』鏄� "yyyy-MM-dd HH:mm:ss" 
	 * @param time
	 * @param endTime
	 * @return 鍗曚綅 绉�
	 */
	public static String getDiffDate(String time, String endTime) {
		if(time==null || endTime==null ||"".equals(time)||"".equals(endTime)){return ""+0;}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d1 = df.parse(time);
			Date d2 = df.parse(endTime);
			long diff = d2.getTime() - d1.getTime();
			long minutes = diff / 1000;
			return "" + minutes;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ""+0;
	}
	public static void writeFile(String canonicalFilename, String text) 
			throws IOException
			{
			  File file = new File (canonicalFilename);
			  BufferedWriter out = new BufferedWriter(new FileWriter(file)); 
			  out.write(text);
			  out.close();
			}
//	public static boolean  isFileExist(String canonicalFilename) 
//			
//			{
//			  File file = new File (canonicalFilename);
//			  if(file.exists()){
//				  return true;
//			  }
//			  return false;
//			}
	public static boolean isFileExist(String path,String filename)
	{
		boolean flag=false;
		try 
		{
			File fNormalPrams = new File(path + filename);
			if (fNormalPrams.exists()) 
			{
				flag = true; 
			}
			else {
				return false;
			}
		}
		catch (Exception e) 
		{
			// TODO: handle exception
			return false;
		}
		return flag;
	}
	public static String bytesToHexString(byte[] src){  
        StringBuilder stringBuilder = new StringBuilder("");  
        if (src == null || src.length <= 0) {  
            return null;  
        }  
        for (int i = 0; i < src.length; i++) {  
            int v = src[i] & 0xFF;  
            String hv = Integer.toHexString(v);  
            if (hv.length() < 2) {  
                stringBuilder.append(0);  
            }  
            stringBuilder.append(hv);  
        }  
        return stringBuilder.toString();  
    }  
	public static byte[] float2byte(float f) {  
	      
		    // 鎶奻loat杞崲涓篵yte[]  
		    int fbit = Float.floatToIntBits(f);  
		      
		    byte[] b = new byte[4];    
		    for (int i = 0; i < 4; i++) {    
		        b[i] = (byte) (fbit >> (24 - i * 8));    
		    }   
		      
		    // 缈昏浆鏁扮粍  
		    int len = b.length;  
		    // 寤虹珛涓�涓笌婧愭暟缁勫厓绱犵被鍨嬬浉鍚岀殑鏁扮粍  
		    byte[] dest = new byte[len];  
		    // 涓轰簡闃叉淇敼婧愭暟缁勶紝灏嗘簮鏁扮粍鎷疯礉涓�浠藉壇鏈�  
		    System.arraycopy(b, 0, dest, 0, len);  
		    byte temp;  
		    // 灏嗛『浣嶇i涓笌鍊掓暟绗琲涓氦鎹�  
		    for (int i = 0; i < len / 2; ++i) {  
		        temp = dest[i];  
		        dest[i] = dest[len - i - 1];  
		        dest[len - i - 1] = temp;  
		    }  
		      
		    return dest;  
		      
		}  
	
	 public static  String getCRC32(byte[] str){
	    	CRC32 crc32 = new CRC32(); 
	    	crc32.update(str); 
	    	return Long.toHexString(crc32.getValue());
	    	
	    }
	 
	 
	 final static int JianGe=6;
	 /**
	  * 
	  * @param CaiyangDian
	  * @param CaiyangPinLv
	  * @param ZhouShu
	  * @return
	  */
	 public static int getReceiveBLEDataTimeOut(int CaiyangDian,int CaiyangPinLv,int ZhouShu){
		 
		 int timeOut=0;
		 timeOut = ZhouShu*1000*(CaiyangDian/(CaiyangPinLv>0?CaiyangPinLv:1))+(CaiyangDian/20 +2)*JianGe+1500;
		 return timeOut;
	 }
	 
	 
	 
}
